const db = require('../db/index.js')
const bcrypt = require('bcryptjs')
const util = require('util')
const query = util.promisify(db.query).bind(db)
    //获取用户列表
exports.getUsers = async(req, res) => {
    let { query: searchName, pagenum, pagesize } = req.query;
    let start = (pagenum - 1) * pagesize; //pagenum=2  pagesize=1
    let length = pagesize;
    let sql1
    let sql2
    if (searchName) {
        sql1 = `select * from sp_manager m left join sp_role r on(m.role_id =r.role_id) where mg_name='${searchName}' limit ${start},${length}`
        sql2 = `select * from sp_manager  where mg_name='${searchName}'`
    } else {
        sql1 = `select * from sp_manager m left join sp_role r on(m.role_id =r.role_id) limit ${start},${length}`
        sql2 = `select * from sp_manager`
    }

    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    let sqlerr = ''
    try {
        let results = await query(sql2)
        obj.data.total = results.length
        obj.data.pagenum = pagenum
    } catch (err) {
        sqlerr = err;
    }
    try {
        let results = await query(sql1)
        for (var i = 0; i < results.length; i++) {
            results[i] = {
                id: results[i].mg_id,
                mobile: results[i].mg_mobile,
                email: results[i].mg_email,
                username: results[i].mg_name,
                mg_state: results[i].mg_state,
                role_name: results[i].role_name ? results[i].role_name : '超级管理员'
            }
        }
        obj.data.users = results
    } catch (err) {
        sqlerr = err;
    }

    if (sqlerr) {
        console.log(sqlerr)
        obj.meta.status = 500;
        obj.meta.msg = "数据库查询错误";
        return res.send(obj);
    } else {
        obj.meta.status = 200;
        obj.meta.msg = "获取列表成功";
        return res.send(obj);
    }



    // select * from mg_mangae limit


    // start = （pagenum - 1） * pagesize 查第2页的数据 每页显示1条
    // length = pagesize

}


//添加用户
exports.addUsers = (req, res) => {
    console.log(req.body)
    let sql1 = 'select * from sp_manager where mg_name=?'
    db.query(sql1, req.body.username, (err, results) => {
        // console.log(results)
        var obj = {
            data: {},
            meta: {
                status: '',
                msg: ''
            }
        }
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            if (results.length !== 0) {
                obj.meta.status = 400;
                obj.meta.msg = '用户名已存在';
                return res.send(obj);
            } else {

                var params = {
                        mg_name: req.body.username,
                        mg_pwd: bcrypt.hashSync(req.body.password, 10),
                        mg_email: req.body.email,
                        mg_mobile: req.body.mobile,
                    }
                    //2.插入语句、
                var sql1 = 'insert into sp_manager set ?'
                    //3.执行数据库语句
                db.query(sql1, params, (err, result) => {
                    if (err) {
                        console.log(err)
                        obj.meta.status = 500;
                        obj.meta.msg = '数据库查询错误';
                        return res.send(obj);
                    } else {
                        console.log(result)
                        if (result.affectedRows === 1) {
                            obj.meta.msg = "注册成功"
                            obj.meta.status = 201
                        } else {
                            obj.meta.msg = "注册失败请重试"
                            obj.meta.status = 400
                        }
                        return res.send(obj)
                    }
                })


            }
        }
    })

}


//1.3.4. 根据 ID 查询用户信息
exports.searchUserById = (req, res) => {
    let id = req.params.id;
    let sql1 = 'select * from sp_manager where mg_id = ?'
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    db.query(sql1, id, (err, results) => {
            if (err) {
                console.log(err);
                obj.meta.status = 500;
                obj.meta.msg = '数据库查询错误';
                return res.send(obj);
            } else {
                if (results.length === 1) {
                    var data1 = {
                        "id": results[0].mg_id,
                        "username": results[0].mg_name,
                        "role_id": results[0].role_id,
                        "mobile": results[0].mg_mobile,
                        "email": results[0].mg_email
                    }
                    obj.meta.msg = '查询成功';
                    obj.meta.status = 200;
                    obj.data = data1;
                    return res.send(obj)
                }
            }
        })
        //根据id查询sp_manager,满足条件返回给前端

}



exports.changeUserState = (req, res) => {
    let { uId, type } = req.params;
    type = type == 'false' ? 0 : 1;
    // console.log(type)
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    let sql1 = 'update sp_manager set ? where mg_id= ?';
    db.query(sql1, [{ mg_state: type }, uId], (err, result) => {
            if (err) {
                console.log(err);
                obj.meta.status = 500;
                obj.meta.msg = '数据库查询错误';
                return res.send(obj);
            } else {
                console.log(result)
                if (result.affectedRows == 1) {
                    obj.meta.status = 200;
                    obj.meta.msg = '设置更新成功';
                    return res.send(obj);
                }
            }
        })
        // return res.send('ok');
}


exports.editUserById = (req, res) => {
    let id = req.params.id;
    let { email, mobile } = req.body;
    let changeValue = {
        mg_mobile: mobile,
        mg_email: email
    }
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    let sql1 = 'update sp_manager set ? where mg_id=?';
    db.query(sql1, [changeValue, id], (err, results) => {
        if (err) {
            console.log(err);
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            if (results.affectedRows == 1) {
                obj.meta.status = 200;
                obj.meta.msg = '更新成功';
                return res.send(obj);
            }
        }
    })

}

exports.deleteUserById = (req, res) => {
    let id = req.params.id
    let sql1 = 'delete from sp_manager where mg_id=?'
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    db.query(sql1, id, (err, results) => {
        if (err) {
            console.log(err);
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        } else {
            console.log(results)
            if (results.affectedRows == 1) {
                obj.meta.status = 200;
                obj.meta.msg = '删除成功';
                return res.send(obj);
            }
        }
    })

}